package com.artisan.provider.web;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

//可用于getw网关
@Component
public class AntiRefreshInterceptor implements HandlerInterceptor {


    /**
     * 引入redis
     */
    @Autowired //用于简化redis操作  在ioc容器中自动被初始化
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 在执行controller 方法之前进行前置执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //防止返回中文乱码
        response.setContentType("text/html;charset=utf-8");
        System.out.println("Pareheader");
        //获取浏览器电脑信息
        String userAgent = request.getHeader("User-Agent");
        String clientIp = request.getRemoteAddr(); //获取客户端的ip
        System.out.println(userAgent);
        //DigetUtils 用于缩减key 信息
        String key = "anti:refresh:"+DigestUtils.md2Hex(clientIp + "_"+userAgent);

        if (redisTemplate.hasKey("anti:refresh:blacklist")){
            //在这个黑名单中是否有这个ip
            if(redisTemplate.opsForSet().isMember("anti:refresh:blacklist",clientIp)){
                response.getWriter().println("您的IP访问异常,已被加入黑名单");
                return false;
            }
        }
        Integer num = (Integer) redisTemplate.opsForValue().get(key); //获取key
        if(num == null){
            // 第一个参数是ip,第二个参数是自定义计数器 第三个是60秒 自动删除
            redisTemplate.opsForValue().set(key,1,60, TimeUnit.SECONDS);
        }else{

            if(num > 30 && num < 100){
                response.getWriter().println("请求过于频繁,请稍后再试");
                redisTemplate.opsForValue().increment(key,1);
                return false;
            }else if(num >= 100){
                response.getWriter().println("您的IP访问异常,已被加入黑名单");
                //将黑名单ip加入到缓存
                redisTemplate.opsForSet().add("anti:refresh:blacklist",key);
                return false;
            }else{
                redisTemplate.opsForValue().increment(key,1);  //给redis的值自增 +1
            }
        }
        return true;
    }
}
